import flask
from flask import request
from flask import jsonify
import openpyxl
from werkzeug.utils import secure_filename

import lstm

server = flask.Flask(__name__)


@server.route('/', methods=['GET'])
def Index():
    return jsonify({'code': 1, 'msg': '访问成功'})


@server.route('/uploadData', methods=['POST'])
def upload_data():
    if 'file' not in request.files or request.files['file'].filename == '':
        return jsonify({'code': 0, 'msg': '没有文件，请上传文件'})

    file = request.files['file']

    if file:
        # 如果file有值
        data = get_excel_data(file)
        excel_data = {
            'year': [d['year'] for d in data],
            'month': [d['month'] for d in data],
            'passengers': [float(d['passengers']) for d in data]
        }
        prediction_data = lstm.calculate_data(excel_data)

        result_data = {
            'data': data,
            'prediction_data': [item for sublist in prediction_data for item in sublist]
        }

        return jsonify({'msg': '成功', 'code': 1, 'data': result_data})


# 获取excel数据，并返回数组
def get_excel_data(file):
    file_name = secure_filename(file.filename)
    file.save(file_name)

    wb = openpyxl.load_workbook(file_name)
    sheet = wb.active

    first_row = [cell.value for cell in sheet[1]]

    rows = sheet.iter_rows(min_col=1, min_row=2, max_row=sheet.max_row)

    data = []
    for row in rows:
        data_obj = {}
        for index, cell in enumerate(row):
            data_obj[first_row[index]] = cell.value
        data.append(data_obj)

    return data


if __name__ == '__main__':
    print('开始运行...')
    server.run(debug=True, port=8080, host='0.0.0.0')
